/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.muqi.app.im.ui;

import java.security.acl.Owner;
import java.util.ArrayList;
import java.util.List;

import com.easemob.EMGroupChangeListener;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.easeui.ui.EaseGroupRemoveListener;
import com.easemob.easeui.utils.EaseUserUtils;
import com.easemob.easeui.widget.EaseAlertDialog;
import com.easemob.easeui.widget.EaseExpandGridView;
import com.easemob.util.EMLog;
import com.easemob.util.NetUtils;

import com.muqi.app.im.qmain.EMHelper;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.ui.UserHomepagerActivity;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.TextView;
import android.widget.Toast;

public class GroupDetailsActivity extends BaseFragmentActivity implements
		OnClickListener {
	private static final String TAG = "GroupDetailsActivity";
	private static final int REQUEST_CODE_ADD_USER = 0;
	private static final int REQUEST_CODE_EXIT = 1;
	private static final int REQUEST_CODE_EXIT_DELETE = 2;
	private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;

	private EaseExpandGridView userGridview;
	private String groupId;

	private Button exitBtn;
	private Button deleteBtn;
	private EMGroup group;
	private GridAdapter adapter;
	private ProgressDialog progressDialog;
	public static GroupDetailsActivity instance;
	String st = "";
	private TextView mTv_num;

	private boolean isOwn = false;
	private GroupRemoveListener groupRemoveListener;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		groupId = getIntent().getStringExtra("groupId");
		if (groupId == null || "".equals(groupId)) {
			finish();
			return;
		}
		group = EMGroupManager.getInstance().getGroup(groupId);
		if (group == null) {
			finish();
			return;
		}
		if (group.getOwner() != null
				&& group.getOwner().equals(
						EMHelper.getInstance().getCurrentUsernName())) {
			isOwn = true;
		}
		setContentView(R.layout.em_activity_group_details);
		instance = this;
		mTv_num = (TextView) findViewById(R.id.tv_num);
		userGridview = (EaseExpandGridView) findViewById(R.id.gridview);
		exitBtn = (Button) findViewById(R.id.btn_exit_grp);
		deleteBtn = (Button) findViewById(R.id.btn_exitdel_grp);

		groupRemoveListener = new GroupRemoveListener();
        EMGroupManager.getInstance().addGroupChangeListener(groupRemoveListener);

		// 保证每次进详情看到的都是最新的group
		showLoading();
		updateGroup();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		String st1 = getResources().getString(R.string.being_added);

		if (resultCode == RESULT_OK) {
			if (progressDialog == null) {
				progressDialog = new ProgressDialog(GroupDetailsActivity.this);
				progressDialog.setMessage(st1);
				progressDialog.setCanceledOnTouchOutside(false);
			}
			switch (requestCode) {
			case REQUEST_CODE_ADD_USER:// 添加群成员
				final String[] newmembers = data
						.getStringArrayExtra("newmembers");
				progressDialog.setMessage(st1);
				progressDialog.show();
				addMembersToGroup(newmembers);
				break;
			case REQUEST_CODE_EXIT: // 退出群

				break;
			case REQUEST_CODE_EXIT_DELETE: // 解散群

				break;

			case REQUEST_CODE_EDIT_GROUPNAME: // 修改群名称

				break;
			default:
				break;
			}
		}
	}

	private void refreshMembers() {
		List<String> members = new ArrayList<String>();
		members.addAll(group.getMembers());
		mTv_num.setText("群组成员 " + (group.getAffiliationsCount()));
		adapter = new GridAdapter(this, R.layout.em_grid, members);
		userGridview.setAdapter(adapter);
	}

	/**
	 * 点击退出群组按钮
	 * 
	 * @param view
	 */
	public void exitGroup(View view) {
		new SweetAlertDialog(mContext, SweetAlertDialog.WARNING_TYPE)
				.setTitleText("确定退出该群吗？").setCancelText("取消")
				.setConfirmText("确定")
				.setCancelClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog) {
						sweetAlertDialog.dismissWithAnimation();

					}
				}).setConfirmClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog) {
						sweetAlertDialog.dismissWithAnimation();
						showLoading();
						exitGrop();

					}
				}).show();

	}

	/**
	 * 点击解散群组按钮
	 * 
	 * @param view
	 */
	public void exitDeleteGroup(View view) {

		new SweetAlertDialog(mContext, SweetAlertDialog.WARNING_TYPE)
				.setTitleText("确定解散该群吗？").setCancelText("取消")
				.setConfirmText("确定")
				.setCancelClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog) {
						sweetAlertDialog.dismissWithAnimation();

					}
				}).setConfirmClickListener(new OnSweetClickListener() {

					@Override
					public void onClick(SweetAlertDialog sweetAlertDialog) {
						sweetAlertDialog.dismissWithAnimation();
						showLoading();
						deleteGrop();

					}
				}).show();
	}

	/**
	 * 退出群组
	 * 
	 * @param groupId
	 */
	private void exitGrop() {
		String st1 = getResources().getString(
				R.string.Exit_the_group_chat_failure);
		new Thread(new Runnable() {
			public void run() {
				try {
					EMGroupManager.getInstance().exitFromGroup(groupId);// 需异步处理
					runOnUiThread(new Runnable() {
						public void run() {
							hideLoading();
							setResult(RESULT_OK);
							finish();
							if (ChatActivity.activityInstance != null)
								ChatActivity.activityInstance.finish();
						}
					});
				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {
							hideLoading();
							Toast.makeText(
									getApplicationContext(),
									getResources()
											.getString(
													R.string.Exit_the_group_chat_failure)
											+ " " + e.getMessage(), 1).show();
						}
					});
				}
			}
		}).start();
	}

	/**
	 * 解散群组
	 * 
	 * @param groupId
	 */
	private void deleteGrop() {
		final String st5 = getResources().getString(
				R.string.Dissolve_group_chat_tofail);
		new Thread(new Runnable() {
			public void run() {
				try {
					EMGroupManager.getInstance().exitAndDeleteGroup(groupId);// 需异步处理
					runOnUiThread(new Runnable() {
						public void run() {
							hideLoading();
							setResult(RESULT_OK);
							finish();
							if (ChatActivity.activityInstance != null)
								ChatActivity.activityInstance.finish();
						}
					});
				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {
							hideLoading();
							Toast.makeText(getApplicationContext(),
									st5 + e.getMessage(), 1).show();
						}
					});
				}
			}
		}).start();
	}

	/**
	 * 增加群成员
	 * 
	 * @param newmembers
	 */
	private void addMembersToGroup(final String[] newmembers) {
		final String st6 = getResources().getString(
				R.string.Add_group_members_fail);
		new Thread(new Runnable() {

			public void run() {
				try {
					// 创建者调用add方法
					if (EMHelper.getInstance().getCurrentUsernName()
							.equals(group.getOwner())) {
						EMGroupManager.getInstance().addUsersToGroup(groupId,
								newmembers);// 需异步处理
					} else {
						EMGroupManager.getInstance().inviteUser(groupId,
								newmembers, null);// 需异步处理
					}
					runOnUiThread(new Runnable() {
						public void run() {
							refreshMembers();
							progressDialog.dismiss();
						}
					});

				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {
							progressDialog.dismiss();
							Toast.makeText(getApplicationContext(),
									st6 + e.getMessage(), 1).show();
						}
					});
				}
			}
		}).start();
	}

	@Override
	public void onClick(View v) {
	}

	/**
	 * 群组成员gridadapter
	 * 
	 * @author admin_new
	 * 
	 */
	private class GridAdapter extends ArrayAdapter<String> {

		private int res;
		public boolean isInDeleteMode;
		private List<String> objects;

		public GridAdapter(Context context, int textViewResourceId,
				List<String> objects) {
			super(context, textViewResourceId, objects);
			this.objects = objects;
			res = textViewResourceId;
			isInDeleteMode = false;
		}

		@Override
		public View getView(final int position, View convertView,
				final ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(getContext()).inflate(res,
						null);
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.iv_avatar);
				holder.textView = (TextView) convertView
						.findViewById(R.id.tv_name);
				holder.badgeDeleteView = (ImageView) convertView
						.findViewById(R.id.badge_delete);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final LinearLayout button = (LinearLayout) convertView
					.findViewById(R.id.button_avatar);
			// 最后一个item，减人按钮
			if (position == getCount() - 1) {
				holder.textView.setText("");
				// 设置成删除按钮
				holder.imageView.setImageResource(R.drawable.user_sub);

				// 如果不是创建者或者没有相应权限，不提供加减人按钮
				if (!group.getOwner().equals(
						EMHelper.getInstance().getCurrentUsernName())) {
					// if current user is not group admin, hide add/remove btn
					convertView.setVisibility(View.INVISIBLE);
				} else { // 显示删除按钮
					if (isInDeleteMode) {
						// 正处于删除模式下，隐藏删除按钮
						convertView.setVisibility(View.INVISIBLE);
					} else {
						// 正常模式
						convertView.setVisibility(View.VISIBLE);
						convertView.findViewById(R.id.badge_delete)
								.setVisibility(View.INVISIBLE);
					}
					final String st10 = getResources().getString(
							R.string.The_delete_button_is_clicked);
					button.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							isInDeleteMode = true;
							notifyDataSetChanged();
						}
					});
				}
			} else if (position == getCount() - 2) { // 添加群组成员按钮
				holder.textView.setText("");
				holder.imageView.setImageResource(R.drawable.user_add);

				// 如果不是创建者或者没有相应权限
				if (!group.isAllowInvites()
						&& !group.getOwner().equals(
								EMHelper.getInstance().getCurrentUsernName())) {
					// if current user is not group admin, hide add/remove btn
					convertView.setVisibility(View.INVISIBLE);
				} else {
					// 正处于删除模式下,隐藏添加按钮
					if (isInDeleteMode) {
						convertView.setVisibility(View.INVISIBLE);
					} else {
						convertView.setVisibility(View.VISIBLE);
						convertView.findViewById(R.id.badge_delete)
								.setVisibility(View.INVISIBLE);
					}
					final String st11 = getResources().getString(
							R.string.Add_a_button_was_clicked);
					button.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {

							// 进入选人页面
							startActivityForResult((new Intent(
									GroupDetailsActivity.this,
									GroupPickContactsActivity.class).putExtra(
									"groupId", groupId)).putExtra(
									"pick_members_type", "AddClubMembers"),
									REQUEST_CODE_ADD_USER);
						}
					});
				}
			} else { // 普通item，显示群组成员
				final String username = getItem(position);
				convertView.setVisibility(View.VISIBLE);
				button.setVisibility(View.VISIBLE);
				EaseUserUtils.setUserNick(username, holder.textView);
				EaseUserUtils.setUserAvatar(getContext(), username,
						holder.imageView);
				if (isInDeleteMode) {
					// 如果是删除模式下，显示减人图标
					convertView.findViewById(R.id.badge_delete).setVisibility(
							View.VISIBLE);
				} else {
					convertView.findViewById(R.id.badge_delete).setVisibility(
							View.INVISIBLE);
				}
				final String st12 = getResources().getString(
						R.string.not_delete_myself);
				final String st13 = getResources().getString(
						R.string.Are_removed);
				final String st14 = getResources().getString(
						R.string.Delete_failed);
				final String st15 = getResources().getString(
						R.string.confirm_the_members);
				button.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {

						if (isInDeleteMode) {
							// 如果是删除自己，return
							if (EMHelper.getInstance().getCurrentUsernName()
									.equals(username)) {
								new EaseAlertDialog(GroupDetailsActivity.this,
										st12).show();
								return;
							}
							if (!NetUtils.hasNetwork(getApplicationContext())) {
								Toast.makeText(
										getApplicationContext(),
										getString(R.string.network_unavailable),
										0).show();
								return;
							}
							EMLog.d("group", "remove user from group:"
									+ username);
							deleteMembersFromGroup(username);
						} else {
							// 头像点击事件
							Intent intent = new Intent();
							intent.putExtra(
									UserHomepagerActivity.IM_OR_MOBILE_OR_USERID,
									username);
							intent.setClass(mContext,
									UserHomepagerActivity.class);
							startActivity(intent);
						}
					}

					/**
					 * 删除群成员
					 * 
					 * @param username
					 */
					protected void deleteMembersFromGroup(final String username) {
						final ProgressDialog deleteDialog = new ProgressDialog(
								GroupDetailsActivity.this);
						deleteDialog.setMessage(st13);
						deleteDialog.setCanceledOnTouchOutside(false);
						deleteDialog.show();
						new Thread(new Runnable() {

							@Override
							public void run() {
								try {

									// 删除被选中的成员
									// 把username从群聊里删除
									EMGroupManager.getInstance()
											.removeUserFromGroup(groupId,
													username);// 需异步处理
									isInDeleteMode = false;
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											deleteDialog.dismiss();
											refreshMembers();

										}
									});

								} catch (final Exception e) {
									deleteDialog.dismiss();
									runOnUiThread(new Runnable() {
										public void run() {
											Toast.makeText(
													getApplicationContext(),
													st14 + e.getMessage(), 1)
													.show();
										}
									});
								}

							}
						}).start();
					}
				});

			}
			return convertView;
		}

		@Override
		public int getCount() {
			return super.getCount() + 2;
		}
	}

	protected void updateGroup() {
		new Thread(new Runnable() {
			public void run() {
				try {
					final EMGroup returnGroup = EMGroupManager.getInstance().getGroupFromServer(groupId);
					// 更新本地数据
					EMGroupManager.getInstance().createOrUpdateLocalGroup(returnGroup);

					runOnUiThread(new Runnable() {
						public void run() {
							hideLoading();
							refreshMembers();
							if (EMHelper.getInstance().getCurrentUsernName()
									.equals(group.getOwner())) {
								// 显示解散按钮
								exitBtn.setVisibility(View.GONE);
								deleteBtn.setVisibility(View.VISIBLE);
							} else {
								// 显示退出按钮
								exitBtn.setVisibility(View.VISIBLE);
								deleteBtn.setVisibility(View.GONE);
							}

						}
					});

				} catch (Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {

						}
					});
				}
			}
		}).start();
	}

	public void back(View view) {
		setResult(RESULT_OK);
		finish();
	}

	@Override
	public void onBackPressed() {
		setResult(RESULT_OK);
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		instance = null;
		if(groupRemoveListener != null){
		    EMGroupManager.getInstance().removeGroupChangeListener(groupRemoveListener);
		}
	}

	private static class ViewHolder {
		ImageView imageView;
		TextView textView;
		ImageView badgeDeleteView;
	}



	public void onBack(View view) {
		finish();
	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onData() {
		// TODO Auto-generated method stub

	}
	/**
     * 监测群组解散或者被T事件
     * 
     */
    private class GroupRemoveListener extends EaseGroupRemoveListener {

        @Override
        public void onUserRemoved(final String groupId, String groupName) {
            finish();
        }

        @Override
        public void onGroupDestroy(final String groupId, String groupName) {
            finish();
        }

    }

}
